package com.gitee.zycra.future.job.manager;

import com.gitee.zycra.future.job.common.model.JobDependence;
import com.gitee.zycra.future.job.common.param.UpdateDependenceParam;
import com.gitee.zycra.future.job.common.util.IdGenerator;
import com.gitee.zycra.future.job.common.util.UserInfoUtil;
import com.gitee.zycra.future.job.dao.JobDependenceDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zycra
 */
@Component
public class JobDependenceManager {

    @Autowired
    private JobDependenceDao jobDependenceDao;

    @Autowired
    private IdGenerator idGenerator;

    /**
     * 批量插入
     *
     * @param updateDependenceParam 批量插入参数
     * @return 插入条数
     */
    public int batchInsertJobDependence(UpdateDependenceParam updateDependenceParam) {
        Long userId = UserInfoUtil.getUserId();
        String username = UserInfoUtil.getUsername();
        Long childScheduleId = updateDependenceParam.getChildScheduleId();
        List<Long> parentScheduleIdList = updateDependenceParam.getParentScheduleIdList();
        List<JobDependence> dependenceList = new ArrayList<>();
        for (Long parentScheduleId : parentScheduleIdList) {
            dependenceList.add(new JobDependence()
                    .setId(idGenerator.nextId())
                    .setChildScheduleId(childScheduleId)
                    .setParentScheduleId(parentScheduleId)
                    .setOperatorId(userId)
                    .setOperatorName(username));
        }
        return jobDependenceDao.batchInsertJobDependence(dependenceList);
    }

    /**
     * 删除子任务的所有父任务依赖
     *
     * @param childScheduleId 子调度信息ID
     * @return 删除条数
     */
    public int deleteChildDependence(Long childScheduleId) {
        return jobDependenceDao.deleteChildDependence(childScheduleId, UserInfoUtil.getUserId(), UserInfoUtil.getUsername());
    }

    /**
     * 根据父调度信息ID查询子任务ID
     *
     * @param parentId 父调度信息ID
     * @return 查询到的数据
     */
    public List<Long> selectChildIdByParentId(Long parentId) {
        return jobDependenceDao.selectChildIdByParentId(parentId);
    }

    /**
     * 根据子调度信息ID查询父任务ID
     *
     * @param childScheduleId 子调度信息ID
     * @return 查询到的数据
     */
    public List<Long> selectParentIdByChildScheduleId(Long childScheduleId) {
        return jobDependenceDao.selectParentIdByChildScheduleId(childScheduleId);
    }

    /**
     * 根据子调度信息ID集合查询父任务ID
     *
     * @param childScheduleIdList 子调度信息ID集合
     * @return 查询到的数据
     */
    public List<Long> selectParentIdByChildScheduleIdList(List<Long> childScheduleIdList) {
        return jobDependenceDao.selectParentIdByChildScheduleIdList(childScheduleIdList);
    }
}
